Param(
    [parameter(Mandatory=$false)][string]$registry,
    [parameter(Mandatory=$false)][bool]$installIstioOnSystem=$false,
    [parameter(Mandatory=$false)][string]$dockerUser,
    [parameter(Mandatory=$false)][string]$dockerPassword,
    [parameter(Mandatory=$false)][string]$externalDns="aks",
    [parameter(Mandatory=$false)][string]$dnsname="eshoptestistio",
    [parameter(Mandatory=$false)][string]$appName="eshop",
    [parameter(Mandatory=$false)][bool]$deployInfrastructure=$true,
    [parameter(Mandatory=$false)][string]$kialiuser="admin",
    [parameter(Mandatory=$false)][string]$kialipasswrd="admin",
    [parameter(Mandatory=$false)][bool]$clean=$true,
    [parameter(Mandatory=$false)][string]$aksName="",
    [parameter(Mandatory=$false)][string]$aksRg="",
    [parameter(Mandatory=$false)][string]$imageTag="latest",
    [parameter(Mandatory=$false)][bool]$useLocalk8s=$false
    )

$dns = $externalDns

# Instalamos Istio
# Specify the Istio version that will be leveraged throughout these instructions
$ISTIO_VERSION="1.0.6"

# Windows
$ProgressPreference = 'SilentlyContinue'; 
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -URI "https://github.com/istio/istio/releases/download/$ISTIO_VERSION/istio-$ISTIO_VERSION-win.zip" -OutFile "istio-$ISTIO_VERSION.zip"
Remove-Item istio-$ISTIO_VERSION -Recurse -ErrorAction Ignore
Expand-Archive -Path "istio-$ISTIO_VERSION.zip" -DestinationPath .

if($installIstioOnSystem -eq $true) {
    New-Item -ItemType Directory -Force -Path "C:\Program Files\Istio"
    mv ./istio-$ISTIO_VERSION/bin/istioctl.exe "C:\Program Files/Istio/"
    $PATH = [environment]::GetEnvironmentVariable("PATH", "User")
    [environment]::SetEnvironmentVariable("PATH", $PATH + "; C:\Program Files\Istio", "User")
}
# Primero Desinstalamos cualquier cosa que haya en el cluster
if ($clean -eq $true) {
    Write-Host "Cleaning previous helm releases..." -ForegroundColor Green
    helm delete --purge $(helm ls -q) 
    kubectl delete -f istio-$ISTIO_VERSION/install/kubernetes/helm/istio/templates/crds.yaml -n istio-system
    Write-Host "Previous releases deleted" -ForegroundColor Green
}

Write-Host "Generating Kiali Credentials" -ForegroundColor Green
#generamos la credenciales para que kiali arranque sin problemas
kubectl -n istio-system create secret generic kiali --from-literal=username=$kialiuser --from-literal=passphrase=$kialipasswrd


Write-Host "Deploying Istio in the cluster" -ForegroundColor Green
helm install istio-$ISTIO_VERSION/install/kubernetes/helm/istio --wait --name istio --namespace istio-system --set global.controlPlaneSecurityEnabled=true --set grafana.enabled=true --set tracing.enabled=true --set kiali.enabled=true 

Write-Host "Setting Up Gateway"
kubectl delete gateway istio-autogenerated-k8s-ingress -n istio-system
kubectl apply -f ./istio/gateway.yml

if ($useLocalk8s -eq $true) {
    $dns="localhost"
    $externalDns="localhost"
} 
else {
    Write-Host "Resolving DNS to Gateway public IP" -ForegroundColor Green
    $ipaddress = $(kubectl get service istio-ingressgateway -n istio-system)[1] | %{ $_.Split('   ')[9];}
    $query = "[?ipAddress!=null]|[?contains([ipAddress], '$ipaddress')].[id]"
    $resid = az network public-ip list --query $query --output tsv
    $jsonresponse = az network public-ip update --ids $resid --dns-name $dnsname
    $externalDns = ($jsonresponse | ConvertFrom-Json).dnsSettings.fqdn
    Write-Host "$externalDns is pointing to Cluster public ip $ipaddress"
}

$useCustomRegistry=$false
if (-not [string]::IsNullOrEmpty($registry)) {
    $useCustomRegistry=$true
    if ([string]::IsNullOrEmpty($dockerUser) -or [string]::IsNullOrEmpty($dockerPassword)) {
        Write-Host "Error: Must use -dockerUser AND -dockerPassword if specifying custom registry" -ForegroundColor Red
        exit 1
    }
}
Write-Host "Begin eShopOnContainers installation using Helm" -ForegroundColor Green

$infras = ("sql-data", "nosql-data", "rabbitmq", "keystore-data", "basket-data")
$charts = ("eshop-common", "apigwmm", "apigwms", "apigwwm", "apigwws", "basket-api","catalog-api", "identity-api", "locations-api", "marketing-api", "mobileshoppingagg","ordering-api","ordering-backgroundtasks","ordering-signalrhub", "payment-api", "webmvc", "webshoppingagg", "webspa", "webstatus", "webhooks-api", "webhooks-web")

if ($deployInfrastructure) {
    foreach ($infra in $infras) {
        Write-Host "Installing infrastructure: $infra" -ForegroundColor Green
        helm install --values app.yaml --values inf.yaml --set app.name=$appName --set inf.k8s.dns=$externalDns --name="$appName-$infra" $infra     
    }
}

foreach ($chart in $charts) {
    Write-Host "Installing: $chart" -ForegroundColor Green
    if ($useCustomRegistry) {
        helm install --set inf.registry.server=$registry --set inf.registry.login=$dockerUser --set inf.registry.pwd=$dockerPassword --set inf.registry.secretName=eshop-docker-scret --values app.yaml --values inf.yaml --values $ingressValuesFile --set app.name=$appName --set inf.k8s.dns=$dns --set image.tag=$imageTag --set image.pullPolicy=Always --name="$appName-$chart" $chart 
    }
    else {
        if ($chart -ne "eshop-common")  {       # eshop-common is ignored when no secret must be deployed
            helm install --values app.yaml --values inf.yaml --set app.name=$appName --set inf.k8s.dns=$externalDns --set image.tag=$imageTag --set image.pullPolicy=Always --name="$appName-$chart" $chart 
        }
    }
}

Write-Host "helm charts installed." -ForegroundColor Green
Write-Host "Appling Virtual Services for routing." -ForegroundColor Green
kubectl apply -f ./istio/virtualservices.yml

Remove-Item istio-$ISTIO_VERSION -Recurse -ErrorAction Ignore
Remove-Item istio-$ISTIO_VERSION.zip -Recurse -ErrorAction Ignore







